Simulation
Entry point for simulation
- class qtealeaves.QuantumGreenTeaSimulation(model, operators, convergence, observables, folder_name_input='input', folder_name_output='output', file_name_input='TTN.in', tn_type: int | type = 6, py_tensor_backend: TensorBackend | None = None, mpo_mode=-1, disentangler=None, has_log_file=False, store_checkpoints=True, tensor_backend=None)[source]
Simulation class containing the model, the operators, the convergence settings, and the observables.
Arguments
- modelinstance of
QuantumModel Defines the model, i.e., the Hamiltonian of the system.
- operatorsinstance of
TNOperators Defines the operators used in the model and the observables.
- convergenceinstance of
TNConvergenceParameters Specifies the convergence parameters for the simulation, for example the bond dimension.
- observablesinstance of
TNObservables Defines which observables to measure in the simulation. For details, check the specific observable class.
- folder_name_inputstr, or callable; optional
Specifies the folder where the input is stored. Will be created if not existing. Path can contain subfolders and can be parametrized via params dictionary. Default to input.
- folder_name_outputstr, or callable; optional
Specifies the folder where the output is stored. Will be created if not existing. Path can contain subfolders and can be parametrized via params dictionary. Default to output.
- tn_typeint | type, optional
Specifies which tensor network ansatz is used. The options are 5 for TTN, 6 for MPS, 7 for aTTN, 8 for TTOs, 9 for LPTNs. 0 is reserved for ED simulations. Passing a type, allows to pass custom TN classes inherited from the Quantum TEA
_AbstractTN; this supports the DMRG kind of working flow, but has its limits when encountering more tricky parts like observables or excited state searches. Default to 6.- py_tensor_backend
TensorBackend Setup for tensor backend in python - here define which tensor class, device, and dtype to use. For now, has to be compatible with the tensor_backend option of simulation configuration. Default to None (resulting in TensorBackend()).
- mpo_modeint, optional
Choosing the MPO representation inside the simulation, where the value -1 enables an auto-selection (falls to iTPO). The other values are TPO via iTPO (0), iTPO (1), iTPO with update (2, for quenches), iTPO with compression (3), and sparse MPO (10, partially enabled), indexed sparse MPO (11, partially enabled) Default to -1.
- disentanglerNone or np.ndarray, optional
If the aTTN is used, the disentangler positions can be passed as a 2d numpy array with n rows and 2 columns, where n is the number of disentanglers. The indices must be passed as python indices starting from 0 in the mapped 1d system. The other option is to set it to None, in that case the disentangler positions are automatically selected if the tensor network is aTTN. Default to None.
- has_log_filebool, optional
Flag if log file should be created instead of writing the output to standard out. If False, all output will go to standard out. Default to False (no log file)
- store_checkpointsbool, optional
If True, the state will be written to a file after each sweep in the ground state search and after each time step in a time evolution. Ground state searches have the option to write checkpoints also after each tensor optimization, which the algorithm can decide on without control by the user. If True, the delete_existing_folder argument in
QuantumGreenTeaSimulation.run()must be False. Default to True.- tensor_backendNone, optional
(Deprecated argument. Any input will be ignored.) Default to None.
Reserved keywords of the simulation dictionary
The following keywords cannot be used for adapting simulations to the needs by the user, but have a predefined meaning. Additional predefined keywords may be imported, e.g., when using a specific model or a specific set of operators.
continue_file : load file at the beginning of the simulation.
use_mpo_from_continue_file : bool (Python only). Use MPO stored in continue file.
seed : seed for random number generators.
SymmetrySector
SymmetryGenerators
SymmetryTypes
Quenches
ed_sparse : bool, use in exact state emulator to switch between sparse and dense Hamiltonian.
sweep_order : defines the sweep order for the statics (python only)
exclude_from_hash : dictionary entries that will be excluded from hash.
num_excited_states : number of excited states to search for.
start_dynamics_from : which state to use for the dynamics.
Details
Checkpoints vs continue files: checkpointing is used to restart the same simulation. Continue files can be used to set the input state across simulations, but the simulation will start always at the beginning with this user-provided input state.
Hashing: hashes are generated to identify that a simulation setup did not change. For example, changes in a simulation which uses checkpoints can be detected this way.
- autoselect_disentangler(params)[source]
Given a number of sites and Hamiltonian, the function automatically chooses the positions for aTTN disentanglers.
The function iterates through all possible pairs and puts the disentanglers according to the following: - we prioritize the disentanglers which support the links of the highest bond dimension, i.e. the ones in the highest layers - we place disentanglers to a position only if it fully lays on the MPO term (this has proved to be a successful tactics) - we skip DE positions which violate the restrictions in check_disentangler_position() function - we skip DE positions which connect the links whose dimensions cannot grow more than maximal bond dimension (lower layers of the tree)
Parameters
- paramsdict
Dictionary with the simulation parameters.
Return
- auto_disnp.array
Disentangler positions.
- check_disentangler_position(params, disentangler_pos)[source]
This function checks if the input disentangler positions are valid and returns them. If the input positions are None, returns the autoselected ones.
Arguments
- params: dict
Dictionary with the simulation parameters.
- disentangler_poslist/array or None
Disentangler positions. If list/array, each row represents one disentangler. If None, the positions are autoselected based on the Hamiltonian.
Return
- disentangler_poslist/array
Disentangler positions - if input was None then returns the autoselected positions, if input was list then returns the array version which is needed for aTTN algorithms. Otherwise returns the input disentangler positions.
- static checkpoint_params_hash(params)[source]
Generate hash of a simulation to identify if checkpointed simulation.
- extend_params(params)[source]
Extend the parameters list and if the number of quantum trajectories is > 1, add to params the trajectory id and seed.
Arguments
- paramsdict or list of dicts
The parameter dictionary or dictionaries, which is required to obtain the output folder.
- get_ansatz_cls(params: dict) type[_AbstractTN][source]
Get and check the ansatz class.
Arguments
params : simulation dictionary.
Returns
ansatz_cls (type[_AbstractTN]) : resolves the ansatz class and checks if it is consistent with the simulation, e.g., number of excited states. It returns the type itself, not an instance. (Also allowed to return StateVector for compatibility.)
Raises
TypeError, QTeaLeavesError, NotImplementedError
- get_dynamic_obs(params)[source]
Return dictionaries with all observables of the static simulation, e.g., the dynamics. You obtain a nested list, the outer list is iterating over the quenches; the inner list over the time steps of each quench.
Arguments
- paramsdict
The parameter dictionary, which is required to obtain the output folder.
- get_groundstate_energy(params)[source]
(DEPRECATED) Rudimentary way to extract the ground state energy via the convergence file.
Arguments
- paramsdict
The parameter dictionary, which is required to obtain the output folder.
Details
Use
get_static_obsin future.
- get_static_obs(params)[source]
Return a dictionary with all observables of the static simulation, e.g., the ground state search. For evolutions in temperature, i.e., LPTNs, a list of dictionaries is returned.
Arguments
- paramsdict
The parameter dictionary, which is required to obtain the output folder.
- run(params, delete_existing_folder=False, nthreads=1)[source]
Run a simulation or multiple simulations possibly via threading.
Arguments
- paramsdict or list of dicts
The parameter dictionary or dictionaries, which is required to obtain the output folder.
- delete_existing_folderbool, optional
If flag is True, existing folder with potential results will be overwritten without warning. If False, an error is raised if the folders already exist. If True, store_checkpoints must be False. Default to False
- nthreadsint, optional
If number of threads greater is one, we launch serial simulations. If greater than one, multiple threads are started to run simulations in parallel. Default to 1.
Details
We auto-select backends depending on the tn_type specified for the simulation.
Exact diagonalization
Python tensor network backend
Fortran tensor network backend
If you run the threaded version, set the OMP_NUM_THREADS and MKL_NUM_THREADS (executable compiled with ifort) accordingly. The number of threads defined here times the OMP_NUM_THREADS should not exceed the number of your processors.
If running the TTN time evolution, workflow is the following:
- #1 Loading the initial TTN state :
This can be either a random TTN, or the TTN read from a user-set file.
- #2 Groundstate search to set the initial condition :
There are two options - initial condition is the groundstate of the specified Hamiltonian, or initial condition is a TTN from file set by a user. The groundstate is found by iterative search, therefore if the initial condition is set by user, put max_iter=0 in convergence parameters. Otherwise, set max_iter>0.
- #3 Perform a time evolution starting from the obtained
initial condition.
- run_single(params, delete_existing_folder=False)[source]
Run simulation specified via the parameter dictionary.
Arguments
- paramsdict
The parameter dictionary, which is required to obtain the output folder.
- delete_existing_folderbool, optional
If flag is True, existing folder with potential results will be overwritten without warning. If False, an error is raised if the folders already exist. If True, store_checkpoints must be False. Default to False
Details
We auto-select backends depending on the tn_type specified for the simulation.
Exact diagonalization
Python tensor network backend
- run_threaded(params, delete_existing_folder=False, nthreads=4)[source]
Run simulation specified via the parameter dictionary.
Arguments
- paramslist
List of the parameter dictionaries, which is required to obtain the output folder.
- delete_existing_folderbool, optional
If flag is True, existing folder with potential results will be overwritten without warning. If False, an error is raised if the folders already exist. If True, store_checkpoints must be False. Default to False
- nthreadsint, optional
Number of threads to start multiple simulations in parallel. Default to 4.
- status(params)[source]
Returns tuple of three integers containing the number of simulations not started, number of simulation started but not finished, and the number of finished simulations.
Arguments
- paramsdict or list of dicts
The parameter dictionary or dictionaries, which is required to obtain the output folder.
- write_input_single(params, delete_existing_folder)[source]
Write the input files for a simulation.
Arguments
- paramsdict
The parameter dictionary, which is required to obtain the output folder.
- delete_existing_folderbool
If flag is True, existing folder with potential results will be overwritten without warning. If False, an error is raised if the folders already exist. If True, store_checkpoints must be False.
- modelinstance of
Tensor network simulation
- class qtealeaves.simulation.tn_simulation.run_tn_simulation(simulation, params)[source]
Run a full simulation with the python tensor network.
Arguments
- simulationinstance of
ATTNSimulation Represents all the information on the simulation.
- paramsdict
Dictionary containing the current parameters for the simulation.
- simulationinstance of
- class qtealeaves.simulation.tn_simulation.update_time_dependent_terms(state, time, params, params_ii, quench, mpo_mode, pos, force_rebuild_mpo=False)[source]
Update the MPO layer according to the time-dependent couplings.
Arguments
state :
_AbtractTN- timefloat
Time of the current step.
- paramsdict
Used as initial starting point if params_ii is None
- params_iidict
Parameters of the system in the last call.
- quench :
Quench instance contains the time-dependent functions.
- mpo_modeint
MPO mode required to decide on how to update the effective operators.
- posint | tuple of ints
Default position of isometry center.
- force_rebuild_mpobool, optional
Force method to re-calculate the MPO
Returns
state : state itself (updated inplace anyway)
- params_iiupdated params dict (to check for time evolution
with constant checks)
- class qtealeaves.simulation.tn_simulation.optimize(state, params, folder_name_output, store_checkpoints, excited_ii, partial_tn_measurements, sweep_order=None)[source]
Optimize the tensor network by optimizing each tensor in the TN a number of times equal to num_sweeps. If not specified in sweep_order, the optimization is defined by state.default_sweep_order method. The number of sweeps and the other details are controlled in
TNConvergenceParametersParameters
- stateinstance of
_AbstractTN State to be optimized.
- paramsdict
Contains parameters for simulation to resolve parameterization.
- folder_name_inputstr
Folder path for output and storing checkpoints.
- store_checkpointsbool
Flag if checkpoints should be stored (True) or not (False).
- excited_iiint
Integer counter for excited states. Needed for storing checkpoints. If only ground state search, set to 0.
- sweep_orderList[int] | List[Tuple[int]] | None, optional
PATH for the optimization, passed as the integer index of the tensor. Default to None.
Returns
_AbstractTNState after optimization (in-place update not posisble for checkpoints).
- np.ndarray[float], shape [n, 2]
Computational time and energy after each sweep
- bool
Status if measurement is required (True) because the state was updated. In case of a loaded checkpoint which returns without additional optimizations, False is returned.
- stateinstance of
Exact state simulation
- class qtealeaves.simulation.ed_simulation.run_ed_simulation(simulation, params)[source]
Run a full simulation with the exact state vector.
Arguments
- simulationinstance of
ATTNSimulation Represents all the information on the simulation.
- paramsdict
Dictionary containing the current parameters for the simulation.
- simulationinstance of
Quench for dynamics simulation
- class qtealeaves.DynamicsQuench(dt_grid, time_evolution_mode=0, measurement_period=1, oqs_mode=0, check_superfluous=True)[source]
Describing a quench of parameters for the dynamics part of a TN simulation. The parameters must be defined as a function taking the time and the simulation dictionary as arguments.
Arguments
- dt_gridnumpy.ndarray, str, callable
Contains the list of time steps, which can differ. Moreover, it can be parameterized and be a callable or string.
- time_evolution_modeint, optional
Defines the time evolution mode. 0 : automatic selector
(Defaults to 1 for tensor networks. For exact diagonalization, defaults to 10 for systems smaller than 10 sites and 11 for others.)
1 : one-tensor TDVP 2 : two-tensor TDVP 3 : two-tensor TDVP (2nd order) 4 : single-tensor TDVP (2nd order) 5 : 9 steps of one-site and one step of two-site TDVP 10 : exact diagonalization with full Hamiltonian matrix generated 11 : exact diagonalization with Krylov Not every network type might support all time evolution modes. Default to 0.
- measurement_periodint, str, callable, optional
Allows to define a measurement period every n time steps. It considers only the time steps, not the time passed. There is always a measurement at the end of the quench. Default to 1.
- oqs_modeint, optional
Controls the open quantum system evolution, where no open quantum is 0, quantum trajectories with jumps is 1, quantum trajectories with norm only is 2, and density matrix evolution (Lindblad master eq.) is 3. Default to 0.
- check_superfluousbool, optional
If
True, a warning is raised whenever a dictionary key is not in the required parameters. Default to True
Details
Open systems implement the Lindblad equation as
\[\frac{d}{dt} \rho = -i [H, \rho] + \sum \gamma (L \rho L^{\dagger} - \frac{1}{2} \{ L^{\dagger} L, \rho \})\]Complex time evolution is enabled if you pass the time step as complex dt in the native python data complex to the dt-grid. Negative imaginary part will lead to cooling, positive imaginary part results in heating and raises a warning. Complex time evolution cannot be combined with open quantum systems. The state will be automatically renormalized.
- eval_numeric_param(elem, params)[source]
Evaluate a numeric parameter which might be defined via the parameter dictionary.
Arguments
- elemcallable, string, or int/float
Defines the parameter either via a function which return the value, a string being an entry in the parameter dictionary, or directly as the numeric value.
- paramsdict
The parameter dictionary, which will be passed to callables and used to evaluate string parameters.
- get_dt_grid(params)[source]
Evaluate the dt grid and return it.
Arguments
- paramsdict
The parameter dictionary, which will be passed to callables and used to evaluate string parameters.
- get_length(params)[source]
Calculate the length of the time grid even for parameterized grids.
Arguments
- paramsdict
The parameter dictionary, which will be passed to callables and used to evaluate string parameters.
- iter_dts()[source]
Generator yielding all the time steps dt within this quench. It returns the delta, not the current time in total.
- iter_params(required_params, params, time_at_start=0.0)[source]
Iterate over the all time steps and the required parameters within. Function returns the time-dependent parameters evaluated at mid-timestep. Moreover, we return the time-dependent parameters at the end of each time step to allow for measurements.
Arguments
- required_paramsOrderedDict
Keys are the required parameters, values are the default values if no function is present.
- paramsdict
Simulation parameter dictionary.
- time_at_startfloat, optional
Time at the beginning of the quench, which allows to take into account previous quenches. Default to 0.0
- iter_params_dts(params)[source]
Iterate over parameters’s time steps. Coupling with a time-step dt greater than zero, are intended for the time evolution. Every second parameter is 0 or -99 and indicating the values are at the end point for the measurements, i.e., doing measurements (zero) or doing no measurement (-99), respectively. Up to now, no other values less or equal to zero are associated with some special meaning.
Arguments
- paramsdict
Simulation parameter dictionary.
Logging
Logging is handled through python’s logging module, giving the user plenty of room
for customization on where (file, console, etc.), how (text formatting), and what to log -
see e.g. Examples/Logging_setup.py. Filtering is mostly based on the severity
level
of the log record and on its source (from which module it was emitted).
If no custom logging setup is provided, qtealeaves will set some defaults:
logging to the console or to a sim.log file in the simulation output folder,
depending on the argument has_log_file passed at simulation initialization.
By default, logs with level “WARNING” or higher will be emitted, except for simulation-wide
log records coming from the qtealeaves.simulation sub-package, for which “INFO” or higher
is logged. When logging to a file we also call logging.captureWarnings() to enable
capturing messages emitted via warnings.warn().
When customizing logging, you have to explicitly set the level of the simulation-wide logger via get_logger(“qtealeaves.simulation”).setLevel(LEVEL) if you want something different from “INFO”. You may also want to enable capturing warnings, regardless of the value passed for has_log_file.